<template>
  <div class="assignment-submission">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>作业提交</h2>
          <el-tag>截止日期：{{ formatDate(assignment.deadline) }}</el-tag>
        </div>
      </template>

      <div class="assignment-info">
        <h3>{{ assignment.title }}</h3>
        <div class="description">{{ assignment.description }}</div>
      </div>

      <el-form :model="submissionForm" label-width="100px" @submit.prevent="submitAssignment">
        <el-form-item label="作业内容" required>
          <el-input
            v-model="submissionForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入作业内容"
          />
        </el-form-item>

        <el-form-item label="附件">
          <el-upload
            :action="uploadUrl"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            multiple
          >
            <el-button type="primary">上传文件</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" native-type="submit" :loading="submitting">
            提交作业
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { format } from 'date-fns'

const route = useRoute()
const router = useRouter()
const assignment = ref({})
const submitting = ref(false)
const uploadUrl = '/api/assignments/upload'

const submissionForm = ref({
  content: '',
  attachments: []
})

const formatDate = (date: string) => {
  return format(new Date(date), 'yyyy-MM-dd HH:mm')
}

const loadAssignment = async () => {
  try {
    const { data } = await fetch(`/api/assignments/${route.params.assignmentId}`).then(res => res.json())
    assignment.value = data
  } catch (error) {
    ElMessage.error('获取作业信息失败')
  }
}

const handleUploadSuccess = (response) => {
  submissionForm.value.attachments.push(response.fileUrl)
  ElMessage.success('文件上传成功')
}

const handleUploadError = () => {
  ElMessage.error('文件上传失败')
}

const submitAssignment = async () => {
  if (!submissionForm.value.content.trim()) {
    ElMessage.warning('请输入作业内容')
    return
  }

  submitting.value = true
  try {
    await fetch(`/api/assignments/${route.params.assignmentId}/submit`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(submissionForm.value)
    })
    ElMessage.success('作业提交成功')
    router.push('/student/assignments')
  } catch (error) {
    ElMessage.error('作业提交失败')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  loadAssignment()
})
</script>

<style scoped>
.assignment-submission {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.assignment-info {
  margin-bottom: 20px;
}

.description {
  margin-top: 10px;
  color: #666;
  white-space: pre-wrap;
}
</style>